<!--
 * @Author: xuwejie 1529315455@qq.com
 * @Date: 2023-10-25 14:11:20
 * @LastEditors: xuwejie 1529315455@qq.com
 * @LastEditTime: 2023-10-26 11:59:02
 * @FilePath: \old-supply-shop_vue\components\ShapeCard\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="content">
    <div class="close" @click="close">
      <img src="../../static/image/close.png" class="img" />
    </div>
    <canvas canvas-id="canvas" ref="canvas" class="shapeBox"> </canvas>
    <div class="btn" @click="download">
      <img src="../../static/image/download.png" class="img" />
    </div>
  </div>
</template>

<script>
import Qrcode from "qrious";
export default {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    // 商品详情数据
    shopInfo: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      info: null,
    };
  },
  watch: {
    shopInfo: {
      handler(newVal) {
        this.info = newVal;
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    var context = uni.createCanvasContext("canvas", this);
    uni.showLoading({
      title: "生成海报中...",
    });
    // 填充背景色，白色
    context.beginPath();
    context.setFillStyle("#ffffff"); // 默认白色
    context.fillRect(0, 0, 350, 450); // fillRect(x,y,宽度，高度)
    // 绘制商品主图
    this.getBase64(this.info.img, (data) => {
      // 将url图片转为了base64的data
      setTimeout(() => {
        context.drawImage(data, 0, 0, 350, 300);

        // 绘制商品名称
        context.beginPath();
        context.setFontSize(16); // 字号
        context.setFillStyle("#333"); // 颜色
        let title = [...this.info.name];
        let arr = this.cutArray(title, 20);
        arr.forEach((item, index) => {
          let titles = item.join("");
          context.fillText(titles, 20, 330 + index * 20);
        });

        // 绘制金额
        context.beginPath();
        context.setFontSize(14); // 字号
        context.setFillStyle("#c5342b"); // 颜色
        let money = `￥${this.info.spu[0].market_price}/${this.info.spu[0].spu_name}`;
        context.fillText(money, 20, 380);

        // 绘制金额
        context.beginPath();
        context.setFontSize(14); // 字号
        context.setFillStyle("#999"); // 颜色
        context.fillText("长按或扫描识别二维码", 20, 410);

        let rootUrl = getApp().globalData.rootUrl;
        // 绘制二维码
        let qr = new Qrcode({
          value: `${rootUrl}/cmp#/subindex/index/shopdetail?id=${this.info.id}`,
        });
        let qrCodeImage = qr.toDataURL();
        context.drawImage(qrCodeImage, 230, 340, 90, 90);
        uni.hideLoading();
        context.draw();
      }, 2000);
    });

  },
  methods: {
    cutArray(array, subLength) {
      let index = 0,
        newArr = [];
      while (index < array.length) {
        newArr.push(array.slice(index, (index += subLength)));
      }
      return newArr;
    },
    download() {
      uni.showLoading({
        title: "生成中...",
      });
      uni.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: 350,
        height: 450,
        destWidth: 375,
        destHeight: 667,
        canvasId: "canvas",
        success: (res) => {
          console.log(res.tempFilePath);
          // #ifdef MP-WEIXIN
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success() {
              uni.showModal({
                title: "保存成功",
                content: "图片已成功保存到相册，快去分享到您的圈子吧",
                showCancel: false,
              });
            },
          });
          // #endif
          // #ifdef H5
          this.exportImage(res.tempFilePath, `${this.info.name}海报生成`);
          // #endif
          uni.hideLoading();
        },
        fail: (err) => {
          console.log(err);
        },
      });
    },
    exportImage(base64str, fileName) {
      // 将base64格式的图片转换成Blob对象
      var arr = base64str.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      // 将Blob对象转换成文件并下载到本地
      var blob = new Blob([u8arr], {
        type: mime,
      });
      var a = document.createElement("a");
      a.download = fileName;
      a.href = URL.createObjectURL(blob);
      a.click();
    },
    saveImageToPhotosAlbumFun() {
      const that = this;
      uni.downloadFile({
        url: that.storeInfo.merchantIconStaticPath, //图片的地址
        success: function (res) {
          const tempFilePath = res.tempFilePath; //通过res中的tempFilePath 得到需要下载的图片地址
          uni.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: () => {
              uni.hideLoading();
              uni.showToast({
                title: "保存成功",
              });
            },
            fail: () => {
              uni.showToast({
                title: "保存失败",
                icon: "error",
              });
            },
            complete: (res) => {
              uni.hideLoading();
            },
          });
        },
      });
    },
    getBase64(url, callback) {
      // #ifdef H5
      var Img = new Image(),
        dataURL = "";
      Img.src = url + "?v=" + Math.random();
      Img.setAttribute("crossOrigin", "Anonymous");
      Img.onload = function () {
        let canvas = document.createElement("canvas"),
          // width = Img.width,
          // height = Img.height;
          width = 350,
          height = 300;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext("2d").drawImage(Img, 0, 0, width, height);
        dataURL = canvas.toDataURL("image/jpeg");
        callback ? callback(dataURL) : null;
      };
      // #endif
    },

    close() {
      this.$emit("close", false);
    },
  },
};
</script>

<style lang='scss' scoped>
.content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba($color: #000000, $alpha: 0.7);
  z-index: 99;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .shapeBox {
    width: 700rpx;
    height: 900rpx;
    background: #fff;
    border-radius: 20rpx;
  }

  .close {
    width: 40rpx;
    height: 40rpx;
    position: relative;
    z-index: 100;
    left: 45%;
    top: -10px;
    .img {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .btn {
    width: 180rpx;
    background: rgba($color: #000000, $alpha: 0.5);
    margin-top: 30rpx;
    border-radius: 45rpx;
    height: 66rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    .img {
      width: 40rpx;
      height: 40rpx;
    }
  }
}
</style>